'nodejs';

require('rhino').install();
const { showToast } = require("toast");
const { createWindow } = require("floating_window")
const LayoutParams = android.view.WindowManager.LayoutParams
const window = Symbol();

class Window {
    constructor(fm) {
        this.fm = fm;
        this[window] = null;
        this.isInit = false;
        init(this);
    }

    async init() {
        if (!this.isInit) {
            try {
                await this[window].show();
                this.isInit = true;
                this.onWindowCreated();
                let params = this[window].window.getWindowLayoutParams();
                params.flags |= LayoutParams.FLAG_FULLSCREEN | LayoutParams.FLAG_LAYOUT_IN_SCREEN | LayoutParams.FLAG_LAYOUT_NO_LIMITS
                |LayoutParams.FLAG_HARDWARE_ACCELERATED;
                this[window].window.updateWindowLayoutParams(params);
            } catch (error) {
                console.log(error);
                showToast('悬浮窗错误' + error);
            }
        }
    }

    setPosition(x, y) {
        this[window].setPosition(x, y);
    }

    setSize(width, height) {
        this[window].setSize(width, height);
    }

    setTouchable(touchable) {
        let params = this[window].window.getWindowLayoutParams();
        if (!params) return;
        if (touchable) {
            params.flags &= ~LayoutParams.FLAG_NOT_TOUCHABLE;
        } else {
            params.flags |= LayoutParams.FLAG_NOT_TOUCHABLE;
        }
        this[window].window.updateWindowLayoutParams(params);
    }

    getX() {
        return this[window].windowBridge.getX();
    }

    getY() {
        return this[window].windowBridge.getY();
    }

    getWidth() {
        return this[window].windowBridge.getWidth();
    }

    getHeight() {
        return this[window].windowBridge.getHeight();
    }

    close() {
        this[window].close();
    }
}

/**
 * 
 * @param {Window} scope 
 */
function init(scope) {
    let win = createWindow();
    let view = scope.onViewCreated();
    win.setView(view);
    scope[window] = win;
}

module.exports = Window;